<template>
    <a-spin :spinning="spinning">
        <div>
            <Toolbar
                :editor="editorRef"
                :defaultConfig="toolbarConfig"
                mode="default"
            />
        </div>
        <Editor
            style="height: 500px; overflow-y: hidden;border: 1px solid #ccc;"
            v-model="$value"
            :defaultConfig="editorConfig"
            mode="default"
            @onCreated="handleCreated"
            @onChange="handleChange"
        />
    </a-spin>
</template>
<script lang="ts" setup>
    import '@wangeditor/editor/dist/css/style.css' // 引入 css
    import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { onBeforeUnmount, ref, shallowRef } from 'vue';


    const props = defineProps<{
        modelValue:string;
        excerpt?:string;
        excerptLength?:number;
        uploadApi : (file:File) => Promise<any>
    }>()

    const emit = defineEmits<{
        (e : 'update:modelValue', value:string) : void
        (e : 'update:excerpt', value:string) : void
        (e : 'selectCover', url:string) : void
    }>()

    const $value = ref<string>('')
    
    if(props.modelValue) {
        $value.value = props.modelValue
    }

    function handleChange() {
        


        emit('update:modelValue', $value.value)


        const excerpt = extractTextFromRichContent($value.value, props.excerptLength || 200)


        emit('update:excerpt', excerpt)


    }

    const spinning = ref(false)


    const editorRef = shallowRef()

    const toolbarConfig = {}
    const editorConfig = {
        MENU_CONF : {
            uploadImage : {
                async customUpload(file, insertFn) {
                    spinning.value = true
                    try {

                        const res = await props.uploadApi(file)
                        
                        // file 即选中的文件
                        // 自己实现上传，并得到图片 url alt href
                        // 最后插入图片
                        if(res.success) {
                            setTimeout(() => {
                                insertFn(import.meta.env.B_NET_STATIC_URL + res.data, '', '')
                            }, 100)
                        

                            const img = new Image();
                            img.src = URL.createObjectURL(file);
                            img.onload = () => {
                                if(img.width >= 200 && img.height >= 200) {
                                    emit('selectCover', res.data)
                                }
                            
                            };
                        }
                        
                    } catch (error) {
                        
                    }

                    spinning.value = false
                    
                }
            },

            uploadVideo : {
                async customUpload(file, insertFn) {
                    spinning.value = true
                    try {

                        const res = await props.uploadApi(file)
                        if(res.success) {
                            insertFn(import.meta.env.B_NET_STATIC_URL + res.data, '', '')
                        }
                        
                        
                    } catch (error) {
                        
                    }

                    spinning.value = false
                    
                }
            }
        },

        placeholder: '请输入内容...'
    }


    // 组件销毁时，也及时销毁编辑器
    onBeforeUnmount(() => {
        const editor = editorRef.value
        if (editor == null) return
        editor.destroy()
    })

    const handleCreated = (editor) => {
      editorRef.value = editor // 记录 editor 实例，重要！
    }





    
function extractTextFromRichContent(html:string, length = 100) {
  let doc = new DOMParser().parseFromString(html, "text/html");

  function getText(node:Element) {
      if (!node) return "";

      // 如果是文本节点，直接返回文本
      if (node.nodeType === Node.TEXT_NODE) {
          return node.nodeValue.trim();
      }

      // 如果是元素节点，遍历子节点
      if (node.nodeType === Node.ELEMENT_NODE) {
          let text = "";
          for (let child of node.childNodes) {
              text += getText(child);
              if (text.length >= length) break; // 获取到足够的文本时停止
          }
          return text.substring(0, length);
      }
      
      return "";
  }

  let textContent = getText(doc.body).replace(/\s+/g, ' ').trim();
  return textContent
  //return textContent.substring(0, length) + (textContent.length > length ? "..." : "");
}



function processRichText(html: string, length = 100): { updatedHtml: string; excerpt: string } {
  // 使用 DOMParser 解析 HTML 字符串
  const parser = new DOMParser();
  const doc = parser.parseFromString(html, "text/html");

  // 将 <img> 标签的 src 属性从 http:// 修改为 https://
  doc.querySelectorAll("img").forEach((img) => {
    const src = img.getAttribute("src");
    if (src && src.startsWith("http://")) {
      img.setAttribute("src", src.replace(/^http:\/\//, "https://"));
    }
  });

  // 将 <video> 标签的 src 属性从 http:// 修改为 https://
  doc.querySelectorAll("video").forEach((video) => {
    const src = video.getAttribute("src");
    if (src && src.startsWith("http://")) {
      video.setAttribute("src", src.replace(/^http:\/\//, "https://"));
    }
    // 将 <source> 子标签的 src 属性从 http:// 修改为 https://
    video.querySelectorAll("source").forEach((source) => {
      const sourceSrc = source.getAttribute("src");
      if (sourceSrc && sourceSrc.startsWith("http://")) {
        source.setAttribute("src", sourceSrc.replace(/^http:\/\//, "https://"));
      }
    });
  });

  // 获取去除 HTML 标签后的纯文本内容
  const fullText = doc.body.textContent?.replace(/\s+/g, " ").trim() || "";

  // 从 fullText 中截取前 length 个字符作为摘要
  const excerpt = fullText.substring(0, length);

  // 获取修改后的 HTML 字符串
  const updatedHtml = doc.body.innerHTML;

  // 返回结果
  return { updatedHtml, excerpt };
}


</script>